package com.cbtx.module_sp.ui.window;


import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cbtx.module.base.SpUtils;
import com.cbtx.module.base.http.GsonUtil;
import com.cbtx.module.base.http.HttpManager;
import com.cbtx.module.base.http.MyRequestCallBack;
import com.cbtx.module.base.ui.BaseActivity;
import com.cbtx.module.common.bean.AppInfoEntity;
import com.cbtx.module.common.http.HttpUrlManager;
import com.cbtx.module_sp.MyApplication;
import com.cbtx.module_sp.R;
import com.cbtx.module_sp.interceptor.HeaderInterceptor;
import com.cbtx.module_sp.ui.activity.AdvActivity;
import com.cbtx.module_sp.ui.activity.MainActivity;
import com.cbtx.module_sp.ui.activity.base.MyBaseVMActivity;
import com.cbtx.module_sp.ui.dialog.LastTimeConfirmDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.txcb.lib.base.AppManager;
import com.txcb.lib.base.utils.FileUtils;
import com.txcb.lib.base.utils.InstallApkUtil;
import com.txcb.lib.base.utils.LogUtil;
import com.txcb.lib.base.utils.ToastUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;


public class FloatVideoWindowService extends Service implements View.OnTouchListener {

    private static final String TAG = "FloatVideoWindowService";

    private WindowManager mWindowManager;
    private WindowManager.LayoutParams wmParams;
    private LayoutInflater inflater;


    //浮动布局view
    private View mFloatingLayout;
    RecyclerView mRvMenu;
    MainMenuAdapter2 menuAdapter;
    View line;
    View clParent;
    ImageView ivHide;
    View ivHideBg;


    final List<MainMenuBean2> mMenuBeanList = new ArrayList<>();

    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    private int mTouchStartX, mTouchStartY, mTouchCurrentX, mTouchCurrentY;
    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    private int mStartX, mStartY, mStopX, mStopY;
    //判断悬浮窗口是否移动，这里做个标记，防止移动后松手触发了点击事件
    private boolean isMove;

    Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();

        mContext = this;
        initWindow();//设置悬浮窗基本参数（位置、宽高等）
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    private void getAppById(int hotelId) {
        String url = HttpUrlManager.APP_LIST + hotelId + "?type=2";
        HttpManager.getInstance("", new HeaderInterceptor(MyApplication.instance.getHeaderMap()))
                .sendGet(
                        url,
                        new HashMap<>(),
                        new MyRequestCallBack<AppInfoEntity>() {

                            @Override
                            public void onSuccess(AppInfoEntity obj) {
                                mMenuBeanList.clear();

                                MainMenuBean2 mainMenuBean2 = new MainMenuBean2();
                                mainMenuBean2.iconId = R.drawable.wifi;
                                mMenuBeanList.add(mainMenuBean2);

                                for (int i = 0; i < obj.data.list.size(); i++) {
                                    MainMenuBean2 bean = new MainMenuBean2();
                                    bean.title = obj.data.list.get(i).appName;
                                    bean.iconUrl = obj.data.list.get(i).appIcon;
                                    bean.apkUrl = obj.data.list.get(i).downloadUrl;
                                    bean.launchIntent = obj.data.list.get(i).packageName;
                                    mMenuBeanList.add(bean);
                                }
                                menuAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onFailure(int error, String msg) {

                            }
                        });
    }


    public void getData() {

        Log.e(TAG, SpUtils.getString("appInfoEntity"));
        AppInfoEntity appInfoEntity = GsonUtil.jsonToBean(SpUtils.getString("appInfoEntity"), AppInfoEntity.class);

        for (int i = 0; i < appInfoEntity.data.list.size(); i++) {
            MainMenuBean2 bean = new MainMenuBean2();
            bean.title = appInfoEntity.data.list.get(i).appName;
            bean.iconUrl = appInfoEntity.data.list.get(i).appIcon;
            bean.apkUrl = appInfoEntity.data.list.get(i).downloadUrl;
            bean.launchIntent = appInfoEntity.data.list.get(i).packageName;
            mMenuBeanList.add(bean);
        }
    }


    public class MyBinder extends Binder {
        public FloatVideoWindowService getService() {
            return FloatVideoWindowService.this;
        }

        public void setWindowShow(boolean isShow) {

            if (isShow) {
                showWindowView();
            } else {
                hideWindowView();
            }
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mFloatingLayout != null) {
            // 移除悬浮窗口
            mWindowManager.removeView(mFloatingLayout);
            mFloatingLayout = null;
        }
    }

    //这是要静默安装的
    private void downloadApk(String downloadUrl, String packageName) {
        if (TextUtils.isEmpty(downloadUrl)) {
            return;
        }
        int indext = downloadUrl.lastIndexOf("/") + 1;
        String fileName = downloadUrl.substring(indext).split("\\?")[0];
        String filePath = FileUtils.getDownloadDir();
        String allPath = filePath + fileName;


//        HttpManager.getInstance("", null)
//                .downloadFile(downloadUrl, filePath, fileName, new HttpManager.OnDownloadListener() {
//                    @Override
//                    public void onDownloadSuccess(String path) {
//
//                    }
//
//                    @Override
//                    public void onDownloading(int progress) {
//                        LogUtil.d("jm_progress:" + progress);
//                    }
//
//                    @Override
//                    public void onDownloadFailed() {
//
//                    }
//                });

        FileDownloader.setup(mContext);
        FileDownloader.getImpl().create(downloadUrl)
                .setPath(filePath + fileName, false)
                .setListener(new FileDownloadSampleListener() {

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        super.error(task, e);
                        Log.e("TAG", "异常：" + e.toString());
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        super.progress(task, soFarBytes, totalBytes);
                        Log.e("TAG", "应用安装进度：" + soFarBytes + "--" + totalBytes);
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        super.completed(task);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (checkIsCanGou(packageName)) {
                                    Intent intent = MyApplication.instance.getPackageManager().getLaunchIntentForPackage(packageName);
                                    startActivity(intent);
                                }
                                if (InstallApkUtil.installSilent(allPath.split("\\?")[0])) {
                                    ToastUtil.showToast("安装完成");
                                }
                                InstallApkUtil.installSilent(allPath);
                            }
                        }, 2000);
                    }
                }).start();
    }

    public static boolean installApp(String apkPath, String packageName) {
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            process = new ProcessBuilder("pm", "install", "-i", packageName, "-r", apkPath).start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {

        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {

            }
            if (process != null) {
                process.destroy();
            }
        }
        Log.e("result", "" + errorMsg.toString());
        //如果含有“success”单词则认为安装成功
        return successMsg.toString().equalsIgnoreCase("success");
    }

    /**
     * 设置悬浮框基本参数（位置、宽高等）
     */
    private void initWindow() {

        mWindowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        //设置好悬浮窗的参数
        wmParams = getParams();
        // 悬浮窗默认显示以左上角为起始坐标
        wmParams.gravity = Gravity.BOTTOM;
        //悬浮窗的开始位置，因为设置的是从左上角开始，所以屏幕左上角是x=0;y=0
        wmParams.y = 120;

        wmParams.format = PixelFormat.TRANSLUCENT;
        //得到容器，通过这个inflater来获得悬浮窗控件
        inflater = LayoutInflater.from(getApplicationContext());
        // 获取浮动窗口视图所在布局
        mFloatingLayout = inflater.inflate(R.layout.window_main_menu, null);

        clParent = mFloatingLayout.findViewById(R.id.cl_parent);

        line = mFloatingLayout.findViewById(R.id.v_line);
        ivHideBg = mFloatingLayout.findViewById(R.id.iv_hide_bg);

        mRvMenu = mFloatingLayout.findViewById(R.id.rv_menu);
        menuAdapter = new MainMenuAdapter2(mMenuBeanList);
        mRvMenu.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));

        mRvMenu.setAdapter(menuAdapter);

        Observable.interval(0, 300, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        getAppById(SpUtils.getInt("storeId", 0));
                    }
                });

        menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (position == 0) {
                    toNetSet();
                    return;
                }

                MainMenuBean2 menuBean2 = mMenuBeanList.get(position);
                AppManager.getInstance().finishActivity(AdvActivity.class);
                if (!checkIsCanGou(menuBean2.launchIntent)) {
                    Toast.makeText(mContext, "应用安装中，请稍后..." + menuBean2.title, Toast.LENGTH_SHORT).show();
                    downloadApk(menuBean2.apkUrl, menuBean2.launchIntent);
                    return;
                }

                if (menuBean2.launchIntent.equals("com.cbtx.tablet")) {
                    handler2.removeCallbacksAndMessages(null);

                    showWindowView();

                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {

                    BaseActivity.Companion.setCanShowAdv(false);
                    start();

                    hideWindowView();
                    Intent intent  = getPackageManager().getLaunchIntentForPackage(menuBean2.launchIntent);
                    if(intent == null){
                        Toast.makeText(mContext, "该应用已停止，请到系统设置-应用中启动该应用" + menuBean2.title, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });


        ivHide = mFloatingLayout.findViewById(R.id.iv_hide);
        ivHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppManager.getInstance().finishActivity(AdvActivity.class);

                if (!mIsShow) {
                    showWindowView();
                } else {
                    hideWindowView();
                }
            }
        });

        // 添加悬浮窗的视图
        mWindowManager.addView(mFloatingLayout, wmParams);
    }

    public void toNetSet() {
        Activity netSetActivity = AppManager.getInstance().currentActivity();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);
            netSetActivity.startActivityForResult(panelIntent, MyBaseVMActivity.RQ_WIFI_SET);
        } else {
            Intent intent = new Intent();
            intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
            intent.putExtra(":settings:show_fragment_as_subsetting", true);
            netSetActivity.startActivityForResult(intent, MyBaseVMActivity.RQ_WIFI_SET);
        }

    }

    public void showWindowView() {
        mIsShow = true;
        mRvMenu.setVisibility(View.VISIBLE);
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;

        mWindowManager.updateViewLayout(mFloatingLayout, wmParams);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) clParent.getLayoutParams();
                layoutParams.width = 600;
                clParent.setLayoutParams(layoutParams);

                wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
                wmParams.x = 0;
                mWindowManager.updateViewLayout(mFloatingLayout, wmParams);
            }
        }, 50);

        rotation(mIsShow);
    }

    public void hideWindowView() {
        mIsShow = false;

        wmParams.x = (MainActivity.Companion.getWindowWith());

        mWindowManager.updateViewLayout(mFloatingLayout, wmParams);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) clParent.getLayoutParams();
                layoutParams.width = 64;
                clParent.setLayoutParams(layoutParams);


                mRvMenu.setVisibility(View.GONE);
                wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
                wmParams.x = (MainActivity.Companion.getWindowWith());
                mWindowManager.updateViewLayout(mFloatingLayout, wmParams);

            }
        }, 50);


        rotation(mIsShow);
    }

    private void rotation(boolean isShow) {

        line.setVisibility(isShow ? View.VISIBLE : View.GONE);

        ivHideBg.setBackgroundResource(isShow ? R.drawable.shape_window_bg_show : R.drawable.shape_window_bg_hide);

        float v1 = 0f;
        float v2 = 0f;

        if (isShow) {

            v1 = 180f;
            v2 = 360f;
        } else {
            v1 = 360f;
            v2 = 180f;
        }


        ObjectAnimator anim = ObjectAnimator.ofFloat(ivHide, "rotation", v1, v2);

        anim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        // 动画的持续时间，执行多久？
        anim.setDuration(500);


        // 正式开始启动执行动画
        anim.start();
    }


    private boolean checkIsCanGou(String launchItent) {
        return new File("/data/data/" + launchItent).exists();
    }

    private WindowManager.LayoutParams getParams() {
        wmParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        //设置可以显示在状态栏上
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;

        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

        return wmParams;
    }


    boolean isNeedBack;

    //触摸事件
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
//
        LogUtil.d("MotionEvent.onTouch");
        return false;
    }

    Handler handler2 = new Handler();

    private void start() {
        handler2.removeCallbacksAndMessages(null);
        handler2.postDelayed(new Runnable() {
            @Override
            public void run() {
                showCloseDialog();
            }
        }, 1000 * 60 * 30);
    }

    private void showCloseDialog() {
        LastTimeConfirmDialog commentConfirmDialog = new LastTimeConfirmDialog(MainActivity.Companion.getMainActivity());

        //只有这样才能弹框
        if (Build.VERSION.SDK_INT >= 26) {//8.0新特性
            commentConfirmDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
        } else {
            commentConfirmDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        }

        commentConfirmDialog.setOnDialogListener(new LastTimeConfirmDialog.OnDialogListener() {
            @Override
            public void onCancel() {

                back();
            }

            @Override
            public void onAgree() {
                start();
                commentConfirmDialog.dismiss();
            }
        });
        commentConfirmDialog.show();
    }

    private void back() {
        isNeedBack = false;

        //在这里实现点击重新回到Activity
        Intent intent = new Intent(FloatVideoWindowService.this, MainActivity.class);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);

        PendingIntent pendingIntent = PendingIntent.getActivity(mFloatingLayout.getContext(), 0, intent, 0);
        try {
            pendingIntent.send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    boolean mIsShow = true;

} 
